#include "file_downloadpage.h"
#include "ui_file_downloadpage.h"
#include "client_sp2.h"
#include <QFile>
#include <QMessageBox>
#include <QDebug>
#include <QTcpSocket>

file_downloadpage::file_downloadpage(QWidget *parent,QString file_name,QString u_name,QString meg_seq,QTcpSocket* c_tcp) :
    QDialog(parent),
    file_name(file_name),
    u_name(u_name),
    meg_seq(meg_seq),
    c_tcp(c_tcp),
    ui(new Ui::file_downloadpage)
{
    ui->setupUi(this);
    ui->file_name_val->setText(file_name);
    ui->peer_name_val->setText(u_name);
    connect(c_tcp,&QTcpSocket::readyRead,this,[=](){
        ack=new ack_str;
        c_tcp->read((char*)ack,sizeof(ack_str));
        if(ack->server_type==7)
        {
            qDebug()<<"收到文件回复";
            gen_file(ack);
        }

    });
    connect(c_tcp,&QTcpSocket::disconnected,this,[=](){
        qDebug()<<"file_download断开链接";
        c_tcp->close();
        c_tcp->deleteLater();
    });
}

void file_downloadpage::gen_file(ack_str* ack)//生成文件
{
    qDebug()<<"文件写入本地";
    QString file_path;//生成保存文件的路径
    file_path+="/home/zarror/";
    file_path.append(file_name);
    buffer.append(ack->file_meg_con);
    QFile file_towrite(file_path);
    file_towrite.open(QIODevice::WriteOnly);
    file_towrite.write(buffer);
    file_towrite.close();
    QMessageBox::critical(this,"完成下载","请在您的文件夹中查看文件");
    this->hide();

}

void file_downloadpage::on_down_load_clicked()
{
    req=new req_str;
    req->server_type=7;//设置服务号
    strcpy(req->file_name,file_name.toUtf8());
    c_tcp->write((char*)req,sizeof(req_str));

}

file_downloadpage::~file_downloadpage()
{
    delete ui;
}


